<!-- 上级菜单选择下拉框 -->
<template>
  <el-tree-select
    clearable
    filterable
    :data="regionsData"
    check-strictly
    default-expand-all
    node-key="id"
    :props="{ label: 'name' }"
    :placeholder="placeholder"
    :model-value="modelValue || void 0"
    class="ele-fluid"
    :popper-options="{ strategy: 'fixed' }"
    @update:modelValue="updateValue"
  >
    <template #default="{ data }">
      <span>{{ data.name }}</span>
    </template>
  </el-tree-select>
</template>

<script setup>
import { ref, computed } from "vue";
import { EleMessage, toTree } from "ele-admin-plus/es";
import { listRegions } from "@/api/base/region";

const props = defineProps({
  /** 选中的菜单 */
  modelValue: [Number, String],
  /** 提示信息 */
  placeholder: {
    type: String,
    default: "请选择上级省市",
  },
});

const emit = defineEmits(["update:modelValue"]);

/** 菜单数据 */
const regionsData = ref([]);

/** 更新选中数据 */
const updateValue = (value) => {
  emit("update:modelValue", value || 0);
};

/** 获取菜单数据 */
const reload = () => {
  listRegions({
    level: [1, 2],
  })
    .then((list) => {
      regionsData.value = toTree({
        data: list,
        idField: "id",
        parentIdField: "parent_code",
      });
    })
    .catch((e) => {
      EleMessage.error(e.message);
    });
};

reload();

defineExpose({ reload });
</script>
